#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "tp2.h"

  void  AdicionaSK(char *buffer, char *titulo, PK *listaSK, int *nSK, FILE *file, FILE *avail, int tm)
  {
    int navail, i=0, b, NRR=0, a=0;
    char test[200];
    PK *found, aux;
    if((*nSK)>0){
      found=BSearch(listaSK,buffer,0,(*nSK)-1);
    }
    else{
      found=NULL;
    }
    if(found==NULL){
      printf("found==NULL\n");
      fread(&navail,1,4,avail);
      if(navail==-1){
        printf("navail==-1\n");
        while(fgets(test,200,file)!=NULL){
          NRR++;
          fseek(file,NRR*204,0);
        }
        printf("%d\n",NRR);
        for(b=0;b<200;b++){
          aux.titulo[b]=titulo[b];
        }
        aux.NRR=-1;
        fwrite(&aux,1,sizeof(PK),file);
      }
      else{
        printf("navail!=-1\n");
        fseek(file,(navail*204)+1,0);
        NRR=navail;
        fread(&navail,1,4,file);
        fseek(avail,0,0);
        fwrite(&navail,1,4,avail);
        fseek(file,NRR*204,0);
        for(b=0;b<200;b++){
          aux.titulo[b]=titulo[b];
        }
        aux.NRR=-1;
        fwrite(&aux,1,sizeof(PK),file);
      }
      if((*nSK)%20==0){
        listaSK=(PK*)realloc(listaSK,((*nSK)+20)*sizeof(PK));
      }
      for(b=0;b<200;b++){
        listaSK[*nSK].titulo[b]=buffer[b];
      }
      listaSK[*nSK].NRR=NRR;
      (*nSK)++;
    }
    else{
      printf("found!=NULL\n");
      fread(&navail,1,4,avail);
      if(navail==-1){
        printf("navail==-1\n");
        while(fgets(test,200,file)!=NULL){
          NRR++;
          fseek(file,NRR*204,0);
        }
        for(b=0;b<200;b++){
          aux.titulo[b]=titulo[b];
        }
        aux.NRR=found->NRR;
        fwrite(&aux,1,sizeof(PK),file);
      }
      else{
        printf("navail!=-1\n");
        fseek(file,(navail*204)+1,0);
        NRR=navail;
        fread(&navail,1,4,file);
        fseek(avail,0,0);
        fwrite(&navail,1,4,avail);
        fseek(file,NRR*204,0);
        for(b=0;b<200;b++){
          aux.titulo[b]=titulo[b];
        }
        aux.NRR=-1;
        fwrite(&aux,1,sizeof(PK),file);
      }
      found->NRR=NRR;
    }
    NRR=0;
    Ordena(listaSK,0,(*nSK)-1);
  }
